package com.zh.kotlin_mvvm.ui

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.media.projection.MediaProjectionManager
import android.os.Build
import android.os.Bundle
import com.xyz.livelib.service.RecordScreenService
import com.zh.common.base.BaseActivity
import com.zh.common.ktx.registerForResult
import com.zh.kotlin_mvvm.databinding.ActivityRecordLiveBinding

class RecordLiveActivity : BaseActivity<ActivityRecordLiveBinding>() {

    private val url = "rtmp://192.168.3.3:1936/live/gC2EqJE2?account=tste"
    private var service: Intent? = null

    private val launcher = registerForResult {
        if (it.resultCode == Activity.RESULT_OK) {
            service = Intent(this, RecordScreenService::class.java)
            service?.let { service ->
                service.putExtra("code", it.resultCode)
                service.putExtra("data", it.data)
                service.putExtra("url", viewBinding.etUrl.text.toString())
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    startForegroundService(service)
                } else {
                    startService(service)
                }
            }
        } else {
            viewBinding.btnOpt.text = "开始录制"
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        val mediaManager =
            getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
        viewBinding.apply {
            etUrl.setText(url)
            btnOpt.setOnClickListener {
                if (btnOpt.text == "开始录制") {
                    btnOpt.text = "停止录制"
                    launcher.launch(mediaManager.createScreenCaptureIntent())
                } else {
                    btnOpt.text = "开始录制"
                    release()
                }
            }
        }
    }

    private fun release() {
        service?.let {
            stopService(it)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        launcher.unregister()
        release()
    }
}